//
//  UserModel.m
//  EraPig
//
//  Created by Mac_Mini on 2021/3/18.
//

#import "UserModel.h"
#import <objc/runtime.h>
#import "NSObject+YYModel.h"
@interface UserModel ()<NSCoding, YYModel>

@end
@implementation UserModel

- (instancetype)initWithCoder:(NSCoder *)coder{
    if (self = [super init]) {
        unsigned int numberOfIvars = 0;
        //成员变量
        Ivar *ivars = class_copyIvarList([self class], &numberOfIvars);
        
        for (int i = 0 ; i < numberOfIvars; i++) {
            Ivar *ivar = &ivars[i];
            const char *name = ivar_getName(*ivar);
            
            NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
            [self setValue:[coder decodeObjectForKey:key] forKey:key];
        }
        
        free(ivars);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder{
    unsigned int numberOfIvars = 0;
    //成员变量
    Ivar *ivars = class_copyIvarList([self class], &numberOfIvars);
    
    for (int i = 0 ; i < numberOfIvars; i++) {
        Ivar *ivar = &ivars[i];
        const char *name = ivar_getName(*ivar);
        
        NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        
        [coder encodeObject:[self valueForKey:key] forKey:key];
    }
    
    free(ivars);
}

+ (NSDictionary<NSString *,id> *)modelCustomPropertyMapper{
    return @{
        @"userId"   : @[@"id",@"userId"],
        @"userNo"   : @[@"memberNo",@"userNo"],
        @"userName" : @[@"nickName",@"userName"],
    };
}

@end


@implementation UserModel (Archive)

+ (void)archive:(UserModel *)userModel{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:userModel];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"user_archive"];
}
+ (UserModel *)unarchive{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_archive"];
    UserModel *userModel = (UserModel *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
    if (!userModel) {
        return [[UserModel alloc]init];
    }
    return userModel;
}
+ (BOOL)isLogin{
    return [UserModel unarchive].userId;
}

/// 操作前判断用户是否登录，如果没有登录就跳转到登录页面
/// @param viewController 发起请求的控制器
/// @param jumpType 跳转方式
+ (BOOL)checkLoginStateFromViewController:(UIViewController *)viewController jumpType:(JumpType)jumpType{
    if (![UserModel isLogin]) {
        if (jumpType == JumpTypeWithPresent) {
//            [viewController presentViewController:[[LoginNavgationController alloc]initWithRootViewController:[[LoginWelcomeViewController alloc]initWithCheckLoginFromController:viewController]] animated:YES completion:nil];
        }else{
//            [viewController.navigationController pushViewController:[[LoginWelcomeViewController alloc]initWithCheckLoginFromController:viewController] animated:YES];
        }
    }
    return [UserModel isLogin];
}
@end
